/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.swta;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.validator.StringValidator.LengthBetweenValidator;

/**
 *
 * @author JKorreck
 */
public class ItemPackageForm extends Form {

    private RequiredTextField titleField = new RequiredTextField("title");
    final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
    private RequiredTextField idField = new RequiredTextField("id");
    private DropDownChoice categoryDropDown;
    Component parent;
    MyItemPackage itemPackage;

    public ItemPackageForm(String id, Component parent) {
        super(id);

        this.parent = parent;
        feedbackPanel.setOutputMarkupId(true);
        MyItemPackage itemPackage = new MyItemPackage();
        this.setModel(new CompoundPropertyModel(itemPackage));


//            this.categoryDropDown = new DropDownChoice("category", CategoryManager.getInstance().getCategoryNames());

        this.add(idField.add(new LengthBetweenValidator(3, 20)));
//            this.add(categoryDropDown);
        this.add(titleField.add(new LengthBetweenValidator(3, 20)));

        this.add(new AjaxSubmitLink("saveLink") {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                ItemPackageForm.this.onSubmit(target);
                target.addComponent(ItemPackageForm.this.parent);
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.addComponent(ItemPackageForm.this.feedbackPanel);
                super.onError(target, form);
            }
        });
        this.add(feedbackPanel);
    }

    private void onSubmit(AjaxRequestTarget target) {
        System.out.println("__________SUBMIT");
        MyItemPackage packageModel = (MyItemPackage) getModelObject();
        System.out.println("______EDITED PACKAGE ITEMS: " + packageModel.getItemList().size());

        packageModel.updatePackage();
        MyItemPackageManager.getInstance().addItemSet(packageModel);
    }

    public void setItemPackage(MyItemPackage itemPackage) {
        this.itemPackage = itemPackage;
    }
}